package com.video.service.client.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.video.commons.utils.StringUtil;
import com.video.entity.ClientGroupTable;
import com.video.entity.ClientMsg;
import com.video.entity.Webcon;
import com.video.mapper.ClientGroupMiddleMapper;
import com.video.mapper.ClientMsgMapper;
import com.video.service.client.IClientService;
import com.video.service.webcon.IWebconService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @Author ken
 * @Time 2018/12/15 14:38
 * @Version 1.0
 */
@Service
public class ClientServiceImpl extends ServiceImpl<ClientMsgMapper, ClientMsg> implements IClientService {

    @Autowired
    private ClientMsgMapper clientMsgMapper;

    @Autowired
    private ClientGroupMiddleMapper clientGroupMiddleMapper;

    @Autowired
    private IWebconService webconService;

    /**
     * 查询所有终端 按状态排序
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public List<ClientMsg> queryList() {
        QueryWrapper<ClientMsg> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("status");
        List<ClientMsg> clientMsgs = clientMsgMapper.selectList(queryWrapper);
        return clientMsgs;
    }

    /**
     * 搜索终端 根据关键词
     * @param keyword
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public List<ClientMsg> searchList(String keyword) {

        if (StringUtil.isNotEmpty(keyword)){
            //不为空就执行关键词查询
            QueryWrapper<ClientMsg> queryWrapper = new QueryWrapper<ClientMsg>()
                    .like("userid", keyword)
                    .or()
                    .like("terminalname", keyword);
            return clientMsgMapper.selectList(queryWrapper);
        } else {
            //为空直接查询全部
            return this.queryList();
        }
    }

    /**
     * 修改终端名称
     * @param userid
     * @param uname
     * @return
     */
    @Override
    @Transactional
    public int updateName(Integer userid, String uname) {
        ClientMsg clientMsg = clientMsgMapper.selectById(userid);
        clientMsg.setTerminalname(uname);
        int result = clientMsgMapper.updateById(clientMsg);
        return result;
    }

    /**
     * 修改终端权限
     * @param userid
     * @param limits
     * @return
     */
    @Override
    @Transactional
    public int updatePowers(Integer userid, Integer[] limits) {
        ClientMsg clientMsg = clientMsgMapper.selectById(userid);
        if(limits != null){
            clientMsg.setLimits(JSON.toJSONString(limits));
        }
        clientMsgMapper.updateById(clientMsg);
        return 1;
    }

    /**
     * 修改主机终端
     * @param uid
     * @return
     */
    @Override
    @Transactional
    public int updateHost(Integer uid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("hosts", 1);
        List<ClientMsg> list = clientMsgMapper.selectList(queryWrapper);
        if(list != null){
            for (ClientMsg clientMsg : list) {
                clientMsg.setHosts(0);
                clientMsgMapper.updateById(clientMsg);
            }
        }

        ClientMsg clientMsg = clientMsgMapper.selectById(uid);
        clientMsg.setHosts(1);
        return clientMsgMapper.updateById(clientMsg);
    }

    /**
     * 获得主机终端
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public ClientMsg getHost() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("hosts", 1);
        return clientMsgMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional
    public int deleteClientByUserId(Integer userid) {
        //删除终端信息
        clientMsgMapper.deleteById(userid);
        //删除终端和群组关系信息
        QueryWrapper<ClientGroupTable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cid", userid);
        clientGroupMiddleMapper.delete(queryWrapper);
        return 1;
    }

    /**
     * 根据分控账号 查询对应的终端列表
     * @param account
     * @return
     */
    @Override
    public List<ClientMsg> queryClientsByWebcon(String keyword, String account) {
        //获得分控信息
        Webcon webcon = webconService.getById(account);
        //获取分控终端信息
        String clients = webcon.getClients();

        List<ClientMsg> clientMsgs = new ArrayList<>();
        //获得分控的终端信息
        String[] split = clients.split("\\|");
        if(split != null){
            Arrays.stream(split).forEach((x) -> {
                //获得所有终端
                String[] sp = x.split("-");

                QueryWrapper<ClientMsg> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("userid", Integer.parseInt(sp[1]));

                //如果关键字不等于空
                if(StringUtil.isNotEmpty(keyword)) {
                    queryWrapper.and(new Consumer<QueryWrapper<ClientMsg>>() {
                        @Override
                        public void accept(QueryWrapper<ClientMsg> clientMsgQueryWrapper) {
                            clientMsgQueryWrapper
                                    .like("userid", "%" + keyword + "%")
                                    .or()
                                    .like("terminalname", "%" + keyword + "%");
                        }
                    });
                }

                //根据终端id查询终端对象
                ClientMsg clientMsg = clientMsgMapper.selectOne(queryWrapper);
                if(clientMsg != null){
                    clientMsgs.add(clientMsg);
                }
            });
        }

        return clientMsgs;
    }

    /**
     * 根据终端id，批量修改终端音量
     * @param volume
     * @param userid
     * @return
     */
    @Override
    public int updateVolume(Integer volume, String[] userid) {
        for (String uid : userid) {
            ClientMsg clientMsg = clientMsgMapper.selectById(uid);
            clientMsg.setVolume(volume + "");
            clientMsgMapper.updateById(clientMsg);
        }
        return 1;
    }

    /**
     * 保存或者修改终端信息 - 群组关系
     * @param clientMsg
     * @return
     */
    @Override
    @Transactional
    public int insertOrUpdate(ClientMsg clientMsg) {
        int result = 0;
        if(clientMsg.getUserid() != null){

            //查询终端是否存在
            ClientMsg msg = clientMsgMapper.selectById(clientMsg.getUserid());

            if (msg == null){
                //如果不存在就添加
                result = clientMsgMapper.insert(clientMsg);
            } else {
                //如果存在就修改
                result = clientMsgMapper.updateById(clientMsg);
            }

            //查询终端和群组的关系是否存在
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("cid", clientMsg.getUserid());
//            queryWrapper.eq("gid", 1);
            if(result > 0 && clientGroupMiddleMapper.selectCount(queryWrapper) == 0) {
                //将群组和终端插入中间表 - 插入到默认群组
                clientGroupMiddleMapper.insert(new ClientGroupTable()
                        .setCid(clientMsg.getUserid())
                        .setGid(1));
            }
        }
        return result;
    }

    /**
     * 修改终端的终端编号
     * @param newId
     * @param oldId
     * @return
     */
    @Transactional
    @Override
    public int updateUserId(Integer newId, Integer oldId) {
        return clientMsgMapper.updateUserId(newId, oldId);
    }

}
